<script setup>
import {defineProps, onMounted, ref} from "vue";
import moment from 'moment'
import {createVision, getVision, updateVision} from "@/api/eyeCare.js";
import {useRouter} from "vue-router";
import ItemPicker from "@/components/ItemPicker/index.vue"
import DatePicker from "@/components/DatePicker/index.vue"
import DoubleField from "@/components/DoubleField/index.vue"
import NumberPicker from "@/components/NumberPicker/index.vue";
import RadioButton from '@/components/RadioButton/index.vue'
import CheckboxButton from "@/components/CheckboxButton/index.vue";
import {
  AL_OPTIONS,
  AXIS_POSITIONS,
  KERATOMETRY,
  SPHERICAL_MIRRORS,
  SPHERICAL_MIRRORS2,
  USED_EYES_DURATION,
  VISIONS,
  SIT_TYPE,
  LIGHT_TYPE,
  WEAR_TYPE,
  ALLERGY,
  OUTDOOR_DURATION,
  GLASSES_TYPE,
  HABIT,
  OVERLAY_MEASURES
} from "@/utils/const.js";
import {showFailToast, showSuccessToast} from "vant";

let now = moment(new Date()).format('YYYY-MM-DD')
const healTime = ref(now)
const loading = ref(false)
const negativeFactor = ref({
  usedEyesDuration: '',
  sitType: [],
  wearType: [],
  lightType: [],
  allergy: []
})
const prevention = ref({
  outdoorDuration: "",
  glassesType: "",
  habit: [],
  overlayMeasures: []
})
const note = ref('')
const router = useRouter()
const formRef = ref()
const leftVision = ref({
      type: 1,
      nakedVision: null,
      ocularAxis: null,
      sphericalMirror: null,
      cylinderMirror: null,
      horizontalKeratometry: null,
      verticalKeratometry: null,
      axisPosition: null
    }
)
const rightVision = ref({
      type: 2,
      nakedVision: null,
      ocularAxis: null,
      sphericalMirror: null,
      cylinderMirror: null,
      horizontalKeratometry: null,
      verticalKeratometry: null,
      axisPosition: null
    }
)
const activeNames = ref([])
const props = defineProps({
  patientId: String,
  id: String
})

let isEdit = false

const initData = () => {
  if (props.id) {
    isEdit = true
    getVision(props.id).then(resp => {
      if (resp.code === 0) {
        leftVision.value = resp.data.leftVision
        rightVision.value = resp.data.rightVision
        healTime.value = resp.data.healTime
        negativeFactor.value = resp.data.negativeFactor ? JSON.parse(resp.data.negativeFactor) : {
          usedEyesDuration: '',
          sitType: [],
          wearType: [],
          lightType: [],
          allergy: []
        }
        prevention.value = resp.data.prevention ? JSON.parse(resp.data.prevention) : {
          outdoorDuration: "",
          glassesType: "",
          habit: "",
          overlayMeasures: ""
        }
        note.value = resp.data.note
      }
    })
  } else {
    isEdit = false
    let visionStr = localStorage.getItem("vision")
    if (visionStr) {
      let vision = JSON.parse(visionStr)
      delete vision.leftVision.id
      delete vision.rightVision.id
      leftVision.value = vision.leftVision
      rightVision.value = vision.rightVision
      healTime.value = vision.healTime
      negativeFactor.value = vision.negativeFactor ? JSON.parse(vision.negativeFactor) : {
        usedEyesDuration: '',
        sitType: [],
        wearType: [],
        lightType: [],
        allergy: []
      }
      prevention.value = vision.prevention ? JSON.parse(vision.prevention) : {
        outdoorDuration: "",
        glassesType: "",
        habit: "",
        overlayMeasures: ""
      }
      note.value = vision.note
    }
  }
}

const handleSave = async () => {
  await formRef.value.validate()
  let param = {
    patientId: props.patientId,
    healTime: healTime.value,
    leftVision: leftVision.value,
    rightVision: rightVision.value,
    negativeFactor: JSON.stringify(negativeFactor.value),
    prevention: JSON.stringify(prevention.value),
    note: note.value
  }
  loading.value = true
  try {
    let resp
    if (!isEdit) {
      resp = await createVision(param)
    } else {
      param.id = props.id
      resp = await updateVision(param)
    }
    if (resp.code === 0) {
      showSuccessToast(resp.message)
      localStorage.setItem("vision", JSON.stringify(param))
      router.back()
    }
  } catch (error) {
    showFailToast(error.response.data.message)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  initData()
})
</script>

<template>
  <van-form ref="formRef">
    <van-cell-group inset>
      <date-picker v-model="healTime"
                   :required="true"
                   :readonly="isEdit"
                   placeholder="请选择验光时间"
                   :rules="[{ required: true, message: '请选择验光时间' }]"/>
    </van-cell-group>
    <van-cell-group inset>
      <van-collapse v-model="activeNames">
        <van-collapse-item title="验光单*" name="1" size="large">
          <van-row>
            <van-col span="8" offset="8">OD 右眼</van-col>
            <van-col span="8" class="title">OS 左眼</van-col>
          </van-row>
          <double-field title="裸眼*" label="视力">
            <template #right>
              <item-picker v-model="rightVision.nakedVision"
                           :options="VISIONS"
                           :required="true"
                           :default-value="5.0"
                           :rules="[{ required: true, message: '请选择' }]"/>
            </template>
            <template #left>
              <item-picker v-model="leftVision.nakedVision"
                           :options="VISIONS"
                           :required="true"
                           :default-value="5.0"
                           :rules="[{ required: true, message: '请选择' }]"/>
            </template>
          </double-field>
          <double-field title="散瞳/小瞳*" label="球镜DS">
            <template #right>
              <number-picker v-model="rightVision.sphericalMirror"
                             :options="SPHERICAL_MIRRORS"
                             :required="true"
                             :default-value="0"
                             :rules="[{ required: true, message: '请选择' }]"/>
            </template>
            <template #left>
              <number-picker v-model="leftVision.sphericalMirror"
                             :options="SPHERICAL_MIRRORS"
                             :required="true"
                             :default-value="0"
                             :rules="[{ required: true, message: '请选择' }]"/>
            </template>
          </double-field>
          <double-field title="散光" label="柱镜DC">
            <template #right>
              <number-picker v-model="rightVision.cylinderMirror"
                             :options="SPHERICAL_MIRRORS2"
                             :default-value="0"/>
            </template>
            <template #left>
              <number-picker v-model="leftVision.cylinderMirror"
                             :options="SPHERICAL_MIRRORS2"
                             :default-value="0"/>
            </template>
          </double-field>
          <double-field title="轴位" label="">
            <template #right>
              <item-picker v-model="rightVision.axisPosition"
                           :options="AXIS_POSITIONS"/>
            </template>
            <template #left>
              <item-picker v-model="leftVision.axisPosition"
                           :options="AXIS_POSITIONS"/>
            </template>
          </double-field>
        </van-collapse-item>
      </van-collapse>
    </van-cell-group>
    <van-cell-group inset>
      <van-collapse v-model="activeNames">
        <van-collapse-item title="眼轴单*" name="2" size="large">
          <van-row>
            <van-col span="8" offset="8">OD 右眼</van-col>
            <van-col span="8">OS 左眼</van-col>
          </van-row>
          <double-field title="眼轴*" label="">
            <template #right>
              <number-picker v-model="rightVision.ocularAxis"
                             :options="AL_OPTIONS"
                             :required="true"
                             :rules="[{ required: true, message: '请选择' }]"/>
            </template>
            <template #left>
              <number-picker v-model="leftVision.ocularAxis"
                             :options="AL_OPTIONS"
                             :required="true"
                             :rules="[{ required: true, message: '请选择' }]"/>
            </template>
          </double-field>
          <double-field title="K1 R1" label="平角膜曲率">
            <template #right>
              <number-picker v-model="rightVision.horizontalKeratometry"
                             :options="KERATOMETRY"/>
            </template>
            <template #left>
              <number-picker v-model="leftVision.horizontalKeratometry"
                             :options="KERATOMETRY"/>
            </template>
          </double-field>
          <double-field title="K2 R2" label="陡角膜曲率">
            <template #right>
              <number-picker v-model="rightVision.verticalKeratometry"
                             :options="KERATOMETRY"/>
            </template>
            <template #left>
              <number-picker v-model="leftVision.verticalKeratometry"
                             :options="KERATOMETRY"/>
            </template>
          </double-field>
        </van-collapse-item>
      </van-collapse>
    </van-cell-group>
    <van-cell-group inset>
      <van-collapse v-model="activeNames">
        <van-collapse-item title="此前负面因素" name="3" size="large">
          <div class="checkbox-container" style="text-align: center">
            <div>日均用眼时长*</div>
            <radio-button :options="USED_EYES_DURATION"
                          v-model="negativeFactor.usedEyesDuration"/>

            <div>用眼姿势问题*</div>
            <checkbox-button :options="SIT_TYPE"
                             v-model="negativeFactor.sitType"
                             :show-none-option="true"/>

            <div>光照情况*</div>
            <checkbox-button :options="LIGHT_TYPE"
                             v-model="negativeFactor.lightType"
                             :show-none-option="true"/>

            <div>戴镜不正确*</div>
            <checkbox-button :options="WEAR_TYPE"
                             v-model="negativeFactor.wearType"
                             :show-none-option="true"/>

            <div>过敏反应*</div>
            <checkbox-button :options="ALLERGY"
                             v-model="negativeFactor.allergy"
                             :show-none-option="true"/>
          </div>
        </van-collapse-item>
      </van-collapse>
    </van-cell-group>
    <van-cell-group inset>
      <van-collapse v-model="activeNames">
        <van-collapse-item title="此前防控措施" name="4" size="large">
          <div class="checkbox-container">
            <div>日户外时长*</div>
            <radio-button :options="OUTDOOR_DURATION"
                          v-model="prevention.outdoorDuration"
                          color="green"/>

            <div>戴镜*</div>
            <radio-button :options="GLASSES_TYPE"
                          v-model="prevention.glassesType"
                          :show-none-option="true"
                          color="green"/>

            <div>戴镜习惯*</div>
            <checkbox-button :options="HABIT"
                             v-model="prevention.habit"
                             :show-none-option="true"
                             color="green"/>

            <div>叠加措施*</div>
            <checkbox-button :options="OVERLAY_MEASURES"
                             v-model="prevention.overlayMeasures"
                             :show-none-option="true"
                             color="green"/>
          </div>
        </van-collapse-item>
      </van-collapse>
    </van-cell-group>
    <van-cell-group inset>
      <van-collapse v-model="activeNames">
        <van-collapse-item title="防控笔记" name="5" size="large">
          <van-field
              v-model="note"
              rows="10"
              autosize
              label=""
              type="textarea"
              maxlength="1000"
              placeholder="写一写防控日记，有助于日后发现孩子敏感因素"
              show-word-limit
          />
        </van-collapse-item>
      </van-collapse>
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button :loading="loading" @click="handleSave" block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<style scoped lang="scss">
h2 {
  font-size: 16px;
  color: #969799;
}

.van-cell-group {
  margin-top: 16px;
}

.van-row {
  align-items: center;
}

:deep(.van-col) {
  text-align: center;

  .title {
    font-size: 16px;
    font-weight: bold;
  }
}

:deep(.van-cell__title, .van-cell__value) {
  text-align: center;
}

.checkbox-container {
  text-align: center;
}
</style>